package com.structure.demo;

import org.apache.commons.lang3.StringUtils;

/**
 * 选择性排序
 * Created by shuttle on 18/10/10.
 */
public class SelectSort {
    /**
     * 需要被排序的数组
     */
    private static int[] arr = {31, 45, 32, 14, 12, 5, 3, 2, 8};
    static int total = 0;

    public static void selectSort() {
        //循环比较次数
        for (int i = 0; i < arr.length - 1; i++) {
            int arrIndex = i;
            int temp;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[arrIndex] > arr[j]) {
                    arrIndex = j;
                }
                total++;
            }
            if (i != arrIndex) {
                temp = arr[i];
                arr[i] = arr[arrIndex];
                arr[arrIndex] = temp;
            }
            char c = ',';
            printArr(i, arr);
        }

        System.out.println("总循环次数：" + total);
    }

    public static void printArr(int k, int[] arr) {
        String str = "";
        for (int i = 0; i < arr.length; i++) {
            str += arr[i] + ",";
        }
        System.out.println("第" + k + "次排序：" + str);
    }

    public static void main(String[] args) {
        selectSort();
    }
}
